<template>
	<view class="content">
		<view class="text-area" style="font-size: 20px">
			{{report_name}}
		</view>

		<view class="padding">
			<navigator class="cu-btn block bg-blue margin-tb-sm lg"
				:url="'/pages/report/do_report?report_id='+report_id">
				填写报备
			</navigator>
			<button class="do_report"
				:data-clipboard-text="cururl+'/#/pages/report/do_report?report_id='+report_id"
				@click="copyDoReport">
				点击复制给团体成员进行报备
			</button>
		</view>

		<view class="margin-lr">
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class="action">
					<text class="cuIcon-circlefill text-olive"></text> 最近报备：
				</view>
				<view class="action">
					<button class="cu-btn bg-green shadow">
						<navigator :url="'/pages/report/report_record?report_id='+report_id">更多</navigator>
					</button>
				</view>
			</view>
			<view class="cu-list menu">
				<view class="cu-item flex"
					v-for="(reportDoneVal, reportDoneIdx) in reportDone"
					:key="reportDoneIdx">
					<view class="flex">
						<text class="cuIcon-title text-olive"></text>
						<navigator :url="'./report_record_detail?record_id='+reportDoneVal._id">{{reportDoneVal.person_name}}</navigator>
					</view>
					<view>{{new Date(reportDoneVal.create_time).Format("MM-dd HH:mm")}}</view>
					<!-- <button class="cu-btn margin-right" @click="rewriteRecord(reportDoneVal._id)">重填</button> -->
					<button class="cu-btn margin-right" @click="deleteRecord(reportDoneVal._id,reportDoneIdx)">删除</button>
				</view>
			</view>
		</view>

		<view class="padding">
			<form @submit="fetchRecord">
				<view class="cu-bar bg-white solid-bottom margin-top">
					<view class="action">
						<text class="text-bold">查看报备情况</text>
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title">状态：</view>
					<view>
						<radio-group name="report_status">
							<label><radio value="1" />已报备</label>
							<label><radio value="2" />未报备</label>
						</radio-group>
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title">最近：</view>
					<picker mode="selector"
						name="report_range"
						:range="rangeList"
						range-key="name"
						:value="rangeIndex"
						@change="selectRange">
						<view class="picker">
							{{rangeList[rangeIndex].name}}
						</view>
					</picker>
				</view>
				<button class="cu-btn block bg-blue margin-tb-sm lg" form-type="submit">查看</button>
			</form>
			<view v-if="reportView.length" id="report_view">
				<view v-if="report_status == 1">
					<view class="cu-list menu">
						<view class="cu-item flex"
							v-for="(reportVal, reportIdx) in reportView"
							:key="reportIdx">
							<view class="flex">
								<text class="cuIcon-title text-olive"></text>
								<view>{{reportVal.person_name}}</view>
							</view>
							<view v-if="reportVal.create_time">{{new Date(reportVal.create_time).Format("MM-dd HH:mm")}}</view>
						</view>
					</view>
				</view>
				<view v-else-if="report_status == 2">
					<view class="grid col-4">
						<view class="margin-top-sm text-center"
							v-for="(reportVal, reportIdx) in reportView"
							:key="reportIdx">
							<button class="cu-btn round">{{reportVal.person_name}}</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="margin-lr">
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class="action">
					<text class="text-bold">导出报备（请在PC浏览器上导出）</text>
				</view>
			</view>
			<view class="cu-list menu">
				<view class="cu-item">
					<text>选择日期：</text>
					<picker mode="date" @change="selectDateChange">
						<button size="mini">{{tipSelectDate||'请选择日期'}}</button>
					</picker>
				</view>
			</view>
			<button class="cu-btn block bg-blue margin-tb-sm lg" @click="fetchReport">导出指定日期的报备</button>
		</view>

	</view>
</template>

<script>
	import Clipboard from 'clipboard';
	import '@/common/js/date.js';
	import Utils from '@/common/js/utils.js';

	export default {
		data() {
			return {
				cururl: "",
				report_id: "",
				report_name: "",

				// reportDetail: {},
				reportDone: [],

				report_status: 0,
				rangeList: [
					{ value: 1, name: '1小时'},
					{ value: 2, name: '2小时'},
					{ value: 3, name: '3小时'},
					{ value: 4, name: '4小时'},
					{ value: 8, name: '8小时'},
					{ value: 12, name: '12小时'},
					{ value: 24, name: '一天'},
					{ value: 72, name: '三天'}
				],
				rangeIndex: 0,
				reportView: [],

				tipSelectDate: '',
			}
		},
		computed: {
			select_in_time: function() {
				return new Date(this.tipSelectDate).getTime()
			}
		},
		onLoad() {
			this.cururl = location.origin;
			this.report_id = this.$route.query.report_id;
			if (this.report_id) {
				this.getReportDetail();
			}
		},
		methods: {
			copyDoReport() {
				var clipboard = new Clipboard('.do_report')
				clipboard.on('success', e => {
					uni.showToast({
						icon: 'none',
						title: '复制成功'
					});
					// 释放内存
					clipboard.destroy()
				})
				clipboard.on('error', e => {
					// 不支持复制
					uni.showToast({
						icon: 'none',
						title: '该浏览器不支持自动复制'
					});
					// 释放内存
					clipboard.destroy()
				})
			},
			getReportDetail() {
				uniCloud.callFunction({
					name: "ha_get_report",
					data: {
						type: 1,
						report_id: this.report_id
					},
					success: ({result}) => {
						// console.log(result)
						if ( result.status === 0 ) {
							// console.log(result.data)
							// this.reportDetail = result.data;
							const {
								name
							} = result.data.self;
							this.report_name = name;
							this.reportDone = result.data.done;
						} else {
							uni.showToast({
								icon: 'none',
								title: `${result.msg || "网络异常，请稍后重试！"}`,
								duration: 1000
							});
						}
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请稍后重试！'
						});
					}
				});
			},
			rewriteRecord(record_id) {
				uniCloud.callFunction({
					name: "ha_update_record",
					data: {
						type: 0,
						record_id
					},
					success: ({result}) => {
						// console.log(result);
						if ( result.status === 0 ) {
							uni.showToast({
								title: `${result.msg || "更新成功！"}`,
								duration: 1000
							});
							// location.reload();
						} else {
							uni.showToast({
								icon: 'none',
								title: `${result.msg || "网络异常，请稍后重试！"}`,
								duration: 1000
							});
						}
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请稍后重试！'
						});
					}
				});
			},
			deleteRecord(record_id,index) {
				uni.showModal({ content: '确认删除吗？', success: (res) => { if (res.confirm) {
					let token = uni.getStorageSync("token");
					let report_id = this.report_id;

					if (token) {
						uniCloud.callFunction({
							name: "ha_del_report_record",
							data: {
								token,
								report_id,
								record_id
							},
							success: ({result}) => {
								// console.log(result);
								if ( result.status === 0 ) {
									uni.showToast({
										title: `${result.msg || "删除成功！"}`,
										duration: 1000
									});
									this.reportDone.splice(index, 1);
								} else {
									uni.showModal({
										content: `${result.msg || "网络异常，请稍后重试！"}`,
										showCancel: false,
										complete: function () {
											uni.navigateTo({url: "/pages/user/user_login"});
										}
									});
								}
							},
							fail() {
								uni.showToast({
									icon: 'none',
									title: '网络异常，请稍后重试！'
								});
							}
						});
					} else {
						uni.navigateTo({url: "/pages/user/user_login"});
					}
				}}});
			},
			selectDateChange(e) {
				// console.log(e.detail);
				this.tipSelectDate = e.detail.value
			},
			fetchReport() {
				// console.log(this.select_in_time);

				if (!this.select_in_time) {
					uni.showToast({
						title: '请选择日期！',
						icon: 'none'
					})
					return;
				}

				// 检查报备id
				if (!this.report_id) {
					uni.showToast({
						title: '出错了！',
						icon: 'none'
					})
					return;
				}

				uni.showModal({ content: '确认导出吗？', success: (res) => { if (res.confirm) {
					uniCloud.callFunction({
						name: "ha_get_record",
						data: {
							report_id: this.report_id,
							type: 0,
							create_time: this.select_in_time
						},
						success: ({result}) => {
							// console.log(result)
							if ( result.status === 0 ) {
								// console.log(result.data)
								// this.exportReport(JSON.stringify(result.data));
								this.exportReport(result.data);
							} else {
								uni.showToast({
									icon: 'none',
									title: `${result.msg || "网络异常，请稍后重试！"}`,
									duration: 1000
								});
							}
						},
						fail() {
							uni.showToast({
								icon: 'none',
								title: '网络异常，请稍后重试！'
							});
						}
					});
				}}});
			},
			exportReport(jsonData) {
				Utils.JSONToExcelConvertor(jsonData,'report_'+new Date().Format("MM月dd日HH点mm分"));
			},
			selectRange: function(e) {
				this.rangeIndex = e.target.value
			},
			fetchRecord(e) {
				// console.log(e.detail.value);
				const {
					report_status,
					report_range
				} = e.detail.value;

				// 检查参数
				if (report_status != 1 && report_status != 2) {
					uni.showModal({
						content: "请选择报备情况！",
						showCancel: false
					})
					return;
				}
				this.report_status = report_status;
				if (report_range >= this.rangeList.length) {
					uni.showToast({
						icon: 'none',
						title: '出错了！'
					});
					return
				}

				// 检查报备id
				if (!this.report_id) {
					uni.showToast({
						title: '出错了！',
						icon: 'none'
					})
					return;
				}

				// 清空现有记录
				this.reportView = [];

				// 查询记录
				uniCloud.callFunction({
					name: "ha_get_record",
					data: {
						report_id: this.report_id,
						type: (report_status == 1)?1:2,
						report_range: this.rangeList[report_range].value
					},
					success: ({result}) => {
						// console.log(result)
						if ( result.status === 0 ) {
							// console.log(result.data)
							this.reportView = result.data;
						} else {
							uni.showToast({
								icon: 'none',
								title: `${result.msg || "网络异常，请稍后重试！"}`,
								duration: 1000
							});
						}
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请稍后重试！'
						});
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background: #f0f0f0;
	}

	.text-area {
		text-align: center;
	}

</style>
